//
//  CPYMVPlayViewController.m
//  TTMusic
//
//  Created by chenpengyu on 16/4/12.
//  Copyright © 2016年 cpy. All rights reserved.
//

#import "CPYMVPlayViewController.h"

@interface CPYMVPlayViewController ()<UIGestureRecognizerDelegate>
@property (nonatomic, strong) AVPlayerItem *item;

@property (nonatomic, strong) TTMusicAVPlayer *player;//播放器对象
@property (nonatomic, strong) UIProgressView *progressView;//播放缓存进度条
@property (nonatomic, strong) UISlider *timeSlider; // 播放进度条
@property (nonatomic, assign) BOOL didPlay;
@property (nonatomic, assign) BOOL isWhole;
@property (nonatomic, assign) BOOL isHidden;
@property (nonatomic, strong) NSTimer *sliderTimer;
@property (nonatomic, strong) NSTimer *timer; // 定时器
@property (nonatomic, strong) AVPlayerLayer *playlayer;
@property (nonatomic, strong) TTMusicBaseView *playView;
@property (nonatomic, strong) TTMusicBaseView *toolBaseView;
@property (nonatomic, strong) UIButton *stopOrPlaybutton;
@property (nonatomic, strong) UIButton *expandButton;
@property (nonatomic, strong) UIButton *removeButton;
@property (nonatomic, strong) TTMusicBaseLabel *timeLabel;
@property (nonatomic, strong) TTMusicBaseLabel *playTimeLabel;
@property (nonatomic, strong) NSString *timeStr;
@property (nonatomic, strong) NSString *timeStr1;


@end

@implementation CPYMVPlayViewController


+ (instancetype)shareMVPlayViewController  {
    static CPYMVPlayViewController *MVPlayViewController = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        MVPlayViewController = [[CPYMVPlayViewController alloc] init];
    });
    return MVPlayViewController;
}

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    Reachability *wifi = [Reachability reachabilityForInternetConnection];
    if ([wifi currentReachabilityStatus] == 0) {
        NSString *note = @"当前没有网络";
        NSString *title = @"提示";
        UIAlertController *alertC = [UIAlertController alertControllerWithTitle:title message:note preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *sure = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [self.navigationController popViewControllerAnimated:YES];
        }];
        [alertC addAction:sure];
        [self presentViewController:alertC animated:YES completion:^{
        }];
    }
}
- (instancetype)init {
    self = [super init];
    if (self) {
        self.style = [TTMusicAVPlayer shareTTMusicAVPlayer].style;
        self.item = [TTMusicAVPlayer shareTTMusicAVPlayer].currentItem;
        self.view.backgroundColor = [UIColor blackColor];
        self.navigationController.navigationBar.translucent = YES;
        // Do any additional setup after loading the view.
        // 单击的Recognizer
        self.item = [TTMusicAVPlayer shareTTMusicAVPlayer].currentItem;
        self.playView = [[TTMusicBaseView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height / 2 - 150, self.view.frame.size.width, 300)];
        [self.view addSubview:_playView];
        UITapGestureRecognizer *singleRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
        //点击的次数
        singleRecognizer.numberOfTapsRequired = 1; // 单击
        singleRecognizer.delegate = self;
        //给self.view添加一个手势监测；
        [self.view addGestureRecognizer:singleRecognizer];
        self.player = [TTMusicAVPlayer shareTTMusicAVPlayer];
        _player.volume = 1.0f;
        _playlayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
        _playlayer.frame = CGRectMake(0, 0, self.view.frame.size.width, 300);
        _playlayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
        [_playView.layer addSublayer:_playlayer];
        self.removeButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _removeButton.frame = CGRectMake(_playView.frame.size.width - 30, 0, 30, 30);
        [_removeButton setBackgroundImage:[UIImage imageNamed:@"VCReturn"] forState:UIControlStateNormal];
        [_removeButton addTarget:self action:@selector(returnPrePage:) forControlEvents:UIControlEventTouchUpInside];
        [_playView addSubview:_removeButton];
        self.toolBaseView = [[TTMusicBaseView alloc] initWithFrame:CGRectMake(0, _playView.frame.size.height - 30, self.view.frame.size.width, 30)];
        _toolBaseView.backgroundColor = [UIColor grayColor];
        _toolBaseView.alpha = 0.6;
        [_playView addSubview:_toolBaseView];
        self.stopOrPlaybutton = [UIButton buttonWithType:UIButtonTypeSystem];
        _stopOrPlaybutton.frame = CGRectMake(10, 0, 30, 30);
        [_stopOrPlaybutton setBackgroundImage:[UIImage imageNamed:@"VCStop"] forState:UIControlStateNormal];
        [_stopOrPlaybutton addTarget:self action:@selector(playOrStopAction:) forControlEvents:UIControlEventTouchUpInside];
        [_toolBaseView addSubview:_stopOrPlaybutton];
        self.timeSlider = [[UISlider alloc] initWithFrame:CGRectMake(45, 4, self.view.frame.size.width - _stopOrPlaybutton.frame.origin.x - 100, 20)];
        _timeSlider.maximumValue = 1.0f;
        _timeSlider.minimumValue = 0.0f;
        [_timeSlider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
        [_timeSlider setThumbImage:[UIImage imageNamed:@"sliderImage"] forState:UIControlStateNormal];
        _sliderTimer = [NSTimer scheduledTimerWithTimeInterval:0.1f target:self selector:@selector(updateSlider) userInfo:nil repeats:YES];
        [_toolBaseView addSubview:_timeSlider];
        self.expandButton = [UIButton buttonWithType:UIButtonTypeSystem];
        _expandButton.tag = 1006;
        _expandButton.frame = CGRectMake(_timeSlider.frame.size.width + _timeSlider.frame.origin.x + 20, 0, 30, 30);
        [_expandButton setBackgroundImage:[UIImage imageNamed:@"plus"] forState:UIControlStateNormal];
        [_expandButton addTarget:self action:@selector(expandVideo:) forControlEvents:UIControlEventTouchUpInside];
        [_toolBaseView addSubview:_expandButton];
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

}
#pragma mark - 隐藏，显示所有按钮
- (void)singleTap:(UITapGestureRecognizer *)sender {
    if (!_isHidden) {
        _toolBaseView.hidden = YES;
        _removeButton.hidden = YES;
        _isHidden = YES;
    }else {
        _toolBaseView.hidden = NO;
        if (_isWhole) {
            _removeButton.hidden = YES;
        }else {
            _removeButton.hidden = NO;
        }
        _isHidden = NO;
    }
}
#pragma mark - 全屏按钮点击事件
- (void)expandVideo:(UIButton *)sender {
    if (!_isWhole) {
        _playView.transform = CGAffineTransformMakeRotation(M_PI / 2);
        _playView.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height);
        _playlayer.frame = _playView.bounds;
        _toolBaseView.frame = CGRectMake(0, self.view.frame.size.width - 30, [UIScreen mainScreen].bounds.size.height, 30);
        _timeSlider.frame = CGRectMake(_stopOrPlaybutton.frame.origin.x + 33, 0, self.view.frame.size.height - 200, _toolBaseView.frame.size.height);
        self.timeLabel = [[TTMusicBaseLabel alloc] initWithFrame:CGRectMake(self.view.frame.size.height - 155, 0, self.view.frame.size.height - 110, 30)];
        _timeLabel.hidden = NO;
        [_toolBaseView addSubview:_timeLabel];
        _expandButton.frame = CGRectMake(self.view.frame.size.height - 60, 0, _timeSlider.frame.origin.y + _timeSlider.frame.size.height + 30, _toolBaseView.frame.size.height);
        [_expandButton setBackgroundImage:[UIImage imageNamed:@"suoxiao "] forState:UIControlStateNormal];
        self.navigationController.navigationBarHidden = YES;
        _removeButton.hidden = YES;
        _isWhole = YES;
    }else {
        _playView.transform = CGAffineTransformIdentity;
        _playView.frame = CGRectMake(0, self.view.frame.size.height / 2 - 150, self.view.frame.size.width, 300);
        _playlayer.frame = CGRectMake(0, 0, self.view.frame.size.width, 300);
        _removeButton.frame = CGRectMake(_playView.frame.size.width - 30, 0, 30, 30);
        _toolBaseView.frame = CGRectMake(0, _playView.frame.size.height - 30, self.view.frame.size.width, 30);
        _stopOrPlaybutton.frame = CGRectMake(10, 0, 30, 30);
        _timeSlider.frame = CGRectMake(45, 4, self.view.frame.size.width - _stopOrPlaybutton.frame.origin.x - 100, 20);
        _expandButton.frame = CGRectMake(_timeSlider.frame.size.width + _timeSlider.frame.origin.x + 20, 0, 30, 30);
        [_expandButton setBackgroundImage:[UIImage imageNamed:@"plus"] forState:UIControlStateNormal];
        _timeLabel.hidden = YES;
        _removeButton.hidden = NO;
        self.navigationController.navigationBar.hidden = NO;
        _isWhole = NO;
    }
}
#pragma mark - 返回的点击事件
- (void)returnPrePage:(UIButton *)sender {
    [TTMusicAVPlayer shareTTMusicAVPlayer].style = self.style;
    if ([self.item isEqual:nil]) {
        [[TTMusicAVPlayer shareTTMusicAVPlayer] pause];
    }
    [[TTMusicAVPlayer shareTTMusicAVPlayer] replaceCurrentItemWithPlayerItem:self.item];
    [[TTMusicAVPlayer shareTTMusicAVPlayer] play];
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}
#pragma mark - 播放与暂停
- (void)playOrStopAction:(UIButton *)sender {
    if (!self.didPlay) {
        [_player pause];
        [_stopOrPlaybutton setBackgroundImage:[UIImage imageNamed:@"VCPlay"] forState:UIControlStateNormal];
        self.didPlay = YES;
    }else {
        [_player play];
        [_stopOrPlaybutton setBackgroundImage:[UIImage imageNamed:@"VCStop"] forState:UIControlStateNormal];
        self.didPlay = NO;
    }
}
#pragma mark - slider关联AVPlayer
- (void)sliderAction:(UISlider *)slider {
    //    参数1:跳转到的时间
    //    参数2:每秒多少帧（fps）
    if (self.player.currentItem.duration.value) {
        [self.player seekToTime:CMTimeMakeWithSeconds(self.player.currentItem.duration.value / self.player.currentItem.duration.timescale * self.timeSlider.value, self.player.currentTime.timescale) completionHandler:^(BOOL finished) {
            [self.player play];
        }];
    }
}
#pragma mark - slider事件
- (void)updateSlider {
    // Update the slider about the music time
    self.timeSlider.value = CMTimeGetSeconds(self.player.currentItem.currentTime) / CMTimeGetSeconds(self.player.currentItem.duration);
    //总时间
    NSInteger totalTime = CMTimeGetSeconds(self.player.currentItem.duration);
    NSInteger minTime = totalTime / 60;
    NSInteger secondTime = totalTime % 60;
    _timeStr = [NSString stringWithFormat:@"%02ld:%02ld", (long)minTime,(long)secondTime];
    //开始时间
    NSInteger totalTime1 = CMTimeGetSeconds(self.player.currentItem.currentTime);
    NSInteger minTime1 = totalTime1 / 60;
    NSInteger secondTime1 = totalTime1 % 60;
    _timeStr1 = [NSString stringWithFormat:@"%02ld:%02ld", (long)minTime1,(long)secondTime1];
    if(![_timeStr isEqualToString:@""] && ![_timeStr1 isEqualToString:@""]) {
        
        _timeLabel.text = [NSString stringWithFormat:@"%@/%@", _timeStr1, _timeStr];
    }
    else {
        _timeLabel.text = @"00:00/00:00";
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)setUrl:(NSString *)url {
    _url = url;
   

}
#pragma mark - url的set方法，播放
- (void)playWithSongMVURL:(NSString *)url {
    
    [_player playWithMVURL:url];
    [self.player play];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
